package com.lj.admin.controller.system;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lj.common.annotation.log.Log;
import com.lj.common.constant.BaseConstant;
import com.lj.common.core.ajax.Result;
import com.lj.common.core.controller.BaseController;
import com.lj.common.core.model.system.SysRole;
import com.lj.common.core.model.system.SysUser;
import com.lj.common.enums.log.BusinessTypeEnum;
import com.lj.system.constants.UserConstants;
import com.lj.system.model.SysPost;
import com.lj.system.service.ISysDeptService;
import com.lj.system.service.ISysPostService;
import com.lj.system.service.ISysRoleService;
import com.lj.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author 小李飞刀
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysPostService postService;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@permission.hasPermission('system:user:list')")
    @GetMapping("/list")
    public Result list(SysUser user) {
        QueryWrapper<SysUser> wrapper = getWrapper(user);
        Page<SysUser> page = new Page<>(user.getPageNum(), user.getPageSize());
        IPage<SysUser> sysUserPage = userService.page(page, wrapper);
        sysUserPage.getRecords().forEach(item -> item.setDept(deptService.getById(item.getDeptId())));
        return Result.success(sysUserPage);
    }

    /**
     * 获取查询条件
     *
     * @param user 用户
     * @return 结果
     */
    private QueryWrapper<SysUser> getWrapper(SysUser user) {
        QueryWrapper<SysUser> wrapper = Wrappers.query();
        wrapper.like(CharSequenceUtil.isNotEmpty(user.getUserName()), UserConstants.COLUMN_USER_NAME, "%" + user.getUserName() + "%");
        wrapper.eq(CharSequenceUtil.isNotEmpty(user.getPhoneNumber()), UserConstants.COLUMN_PHONE_NUMBER, user.getPhoneNumber());
        wrapper.eq(CharSequenceUtil.isNotEmpty(user.getStatus()), UserConstants.COLUMN_STATUS, user.getStatus());
        wrapper.and(ObjectUtil.isNotEmpty(user.getDeptId()), query -> query.eq(UserConstants.COLUMN_DEPT_ID, user.getDeptId()).or().inSql(UserConstants.COLUMN_DEPT_ID, "SELECT dept_id FROM sys_dept  WHERE find_in_set(" + user.getDeptId() + ", ancestors) "));
        if (ObjectUtil.isNotNull(user.getParams())) {
            if (user.getParams().containsKey(BaseConstant.BEGIN_TIME) && ObjectUtil.isNotNull(user.getParams().get(BaseConstant.BEGIN_TIME))) {
                wrapper.ge(UserConstants.COLUMN_CREATE_TIME, user.getParams().get(BaseConstant.BEGIN_TIME));
            }
            if (user.getParams().containsKey(BaseConstant.END_TIME) && ObjectUtil.isNotNull(user.getParams().get(BaseConstant.END_TIME))) {
                wrapper.le(UserConstants.COLUMN_CREATE_TIME, user.getParams().get(BaseConstant.END_TIME));
            }
        }
        return wrapper;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@permission.hasPermission('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public Result getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        Result ajax = Result.success();
        List<SysRole> roles = roleService.list();
        // 角色下拉选项
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        // 岗位下拉选项
        ajax.put("posts", postService.list());
        if (ObjectUtil.isNotNull(userId)) {
            ajax.put(Result.DATA_TAG, userService.getById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId).stream().map(SysPost::getPostId).collect(Collectors.toList()));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId).stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }


    /**
     * 新增用户
     */
    @PreAuthorize("@permission.hasPermission('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody SysUser user) {
        return userService.addUser(user);
    }


    /**
     * 修改用户
     */
    @PreAuthorize("@permission.hasPermission('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public Result edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        return userService.updateUser(user);
    }


    /**
     * 删除用户
     */
    @PreAuthorize("@permission.hasPermission('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{userIds}")
    public Result remove(@PathVariable Long[] userIds) {
        if (ArrayUtil.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.removeByIds(Arrays.asList(userIds)));
    }


    /**
     * 重置密码
     */
    @PreAuthorize("@permission.hasPermission('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping("/resetPwd")
    public Result resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.resetPwd(user));
    }


    /**
     * 状态修改
     */
    @PreAuthorize("@permission.hasPermission('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.updateUserStatus(user));
    }

    // @Log(title = "用户管理", businessType = BusinessTypeEnum.EXPORT)
    // @PreAuthorize("@ss.hasPermi('system:user:export')")
    // @PostMapping("/export")
    // public void export(HttpServletResponse response, SysUser user) {
    //     List<SysUser> list = userService.selectUserList(user);
    //     ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
    //     util.exportExcel(response, list, "用户数据");
    // }
    //
    // @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    // @PreAuthorize("@ss.hasPermi('system:user:import')")
    // @PostMapping("/importData")
    // public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
    //     ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
    //     List<SysUser> userList = util.importExcel(file.getInputStream());
    //     String operName = getUsername();
    //     String message = userService.importUser(userList, updateSupport, operName);
    //     return AjaxResult.success(message);
    // }
    //
    // @PostMapping("/importTemplate")
    // public void importTemplate(HttpServletResponse response) {
    //     ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
    //     util.importTemplateExcel(response, "用户数据");
    // }
    //


    //
    // /**
    //  * 根据用户编号获取授权角色
    //  */
    // @PreAuthorize("@ss.hasPermi('system:user:query')")
    // @GetMapping("/authRole/{userId}")
    // public AjaxResult authRole(@PathVariable("userId") Long userId) {
    //     AjaxResult ajax = AjaxResult.success();
    //     SysUser user = userService.selectUserById(userId);
    //     List<SysRole> roles = roleService.selectRolesByUserId(userId);
    //     ajax.put("user", user);
    //     ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
    //     return ajax;
    // }
    //
    // /**
    //  * 用户授权角色
    //  */
    // @PreAuthorize("@ss.hasPermi('system:user:edit')")
    // @Log(title = "用户管理", businessType = BusinessType.GRANT)
    // @PutMapping("/authRole")
    // public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
    //     userService.insertUserAuth(userId, roleIds);
    //     return success();
    // }
}